package server

import (
	"context"
	v1 "geekbang-go-homework/week04/api/order/v1"
	"geekbang-go-homework/week04/internal/conf"
	"geekbang-go-homework/week04/pkg/middleware/logging"
	"geekbang-go-homework/week04/pkg/middleware/recover"
	"geekbang-go-homework/week04/pkg/transport/http"

	"google.golang.org/grpc/grpclog"

	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)

func NewHTTPServer(conf *conf.Bootstrap, log grpclog.LoggerV2, server v1.OrderApiServer) (*http.Server, error) {
	mux := runtime.NewServeMux()
	err := v1.RegisterOrderApiHandlerServer(context.Background(), mux, server)
	if err != nil {
		return nil, err
	}
	return http.NewServer(append([]http.ServerOption{
		http.WithHandler(mux),
		http.WithLog(log),
		http.WithMiddleware(recover.Recover(), logging.Logging(log)),
	}, getHTTPServerOptions(conf)...)...), nil
}

func getHTTPServerOptions(conf *conf.Bootstrap) []http.ServerOption {
	if conf.GetServer().GetHttp() == nil {
		return nil
	}
	var opts []http.ServerOption
	if conf.Server.Http.Network != "" {
		opts = append(opts, http.WithNetwork(conf.Server.Http.Network))
	}
	if conf.Server.Http.Addr != "" {
		opts = append(opts, http.WithAddress(conf.Server.Http.Addr))
	}
	if conf.Server.Http.GetTimeout().IsValid() {
		opts = append(opts, http.WithTimeout(conf.Server.Http.Timeout.AsDuration()))
	}
	return opts
}
